<?php
define('DIR_IMAGE', Yii::app()->params['imageUploadPath']);
class FilemanagerController extends CController
{
    
    public $layout='//layouts/column3';
    
    
	public function actionIndex()
	{
        $data = array();
        if (isset($_GET['field'])) {
            $data['field'] = $_GET['field'];
        } else {
            $data['field'] = '';
        }
        
        if (isset($_GET['CKEditorFuncNum'])) {
           $data['fckeditor'] = $_GET['CKEditorFuncNum'];
        } else {
           $data['fckeditor'] = false;
        }
		$this->render('index',array(
                    'data' => $data));
	}
    
    public function actionDirectory(){
         $json = array();
         $directories = glob(rtrim(DIR_IMAGE . '/' . str_replace('../', '', $_POST['directory']), '/') . '/*', GLOB_ONLYDIR);
         //echo $directories; 
         //echo DIR_IMAGE . 'data/' . str_replace('../', '', $_POST['directory']); 
        if ($directories) {
            $i = 0;
        
            foreach ($directories as $directory) {
                $json[$i]['data'] = basename($directory);
                $json[$i]['attributes']['directory'] = substr($directory, strlen(DIR_IMAGE . '/'));
                
                $children = glob(rtrim($directory, '/') . '/*', GLOB_ONLYDIR);
                
                if ($children)  {
                    $json[$i]['children'] = ' ';
                }
                
                $i++;
            }
        }
        
        $jsonData = Json::encode($json);
        //echo $jsonData;
        $this->renderText($jsonData);
    }
    
    public function actionFiles(){
       $json = array();
        if (isset($_POST['directory']) && $_POST['directory']) {
            $directory = DIR_IMAGE . '/' . str_replace('../', '', $_POST['directory']);
        } else {
            $directory = DIR_IMAGE . '/';
        }
        
        $allowed = array(
            '.jpg',
            '.jpeg',
            '.png',
            '.gif'
        );
        
        $files = glob(rtrim($directory, '/') . '/*');
        
        if ($files) {
            foreach ($files as $file) {
                if (is_file($file)) {
                    $ext = strrchr($file, '.');
                } else {
                    $ext = '';
                }    
                
                if (in_array(strtolower($ext), $allowed)) {
                    $size = filesize($file);
        
                    $i = 0;
        
                    $suffix = array(
                        'B',
                        'KB',
                        'MB',
                        'GB',
                        'TB',
                        'PB',
                        'EB',
                        'ZB',
                        'YB'
                    );
        
                    while (($size / 1024) > 1) {
                        $size = $size / 1024;
                        $i++;
                    }
                        
                    $json[] = array(
                        'file'     => "/upload/".substr($file, strlen(DIR_IMAGE . '/')),
                        'filename' => basename($file),
                        'size'     => round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i],
                        'thumb'    => Yii::app()->request->baseUrl."/upload/".substr($file, strlen(DIR_IMAGE . '/'))
                        /*,
                        'thumb'    => Image::resize(substr($file, strlen(DIR_IMAGE)), 100, 100)          */
                    );
                }
            }
        }
        
        //echo $jsonData;
        $this->renderText(Json::encode($json));
    }
    
    public function actionUpload() {
        $json = array();
        if (isset($_POST['directory'])) {
            if (isset($_FILES['image']) && $_FILES['image']['tmp_name']) {
                if ((strlen(utf8_decode($_FILES['image']['name'])) < 3) || (strlen(utf8_decode($_FILES['image']['name'])) > 255)) {
                   $json['error'] = 'Warning: Filename must be a between 3 and 255!';
                }
                    
                $directory = rtrim(DIR_IMAGE . '/' . str_replace('../', '', $_POST['directory']), '/');
                
                if (!is_dir($directory)) {
                    $json['error'] = 'Warning: Please select a directory!';
                }
                
                if ($_FILES['image']['size'] > 1000000) {
                   $json['error'] = 'Warning: File to big please keep below 300kb and no more than 1000px height or width!';
                }
                
                $allowed = array(
                    'image/jpeg',
                    'image/pjpeg',
                    'image/png',
                    'image/x-png',
                    'image/gif',
                    'application/x-shockwave-flash'
                );
                        
                if (!in_array($_FILES['image']['type'], $allowed)) {
                    $json['error'] = 'Warning: Incorrect file type!';
                }
                
                $allowed = array(
                    '.jpg',
                    '.jpeg',
                    '.gif',
                    '.png',
                    '.flv'
                );
                        
                if (!in_array(strtolower(strrchr($_FILES['image']['name'], '.')), $allowed)) {
                    $json['error'] = 'Warning: Incorrect file type!';
                }

                
                if ($_FILES['image']['error'] != UPLOAD_ERR_OK) {
                   $json['error'] = 'error_upload_' .$_FILES['image']['error'];
                }            
            } else {
               $json['error'] = 'Warning: Please select a file!';
            }
        } else {
            $json['error'] = 'Warning: Please select a directory!';
        }
        
       /* if (!$this->user->hasPermission('modify', 'common/filemanager')) {
              $json['error'] = $this->language->get('error_permission');  
        }  */
        
        if (!isset($json['error'])) {    
            if (@move_uploaded_file($_FILES['image']['tmp_name'], $directory . '/' . basename($_FILES['image']['name']))) {        
               $json['success'] = 'Success: Your file has been uploaded!';
            } else {
               $json['error'] = 'Warning: File could not be uploaded for an unknown reason!';
            }
        }
        
       /* $this->load->library('json');
        
        $this->response->setOutput(Json::encode($json));
        */
        
         $this->renderText(Json::encode($json));
    }
    
    public function actionCreate() {                
        $json = array();
        
        if (isset($_POST['directory'])) {
            if (isset($_POST['name']) || $_POST['name']) {
                $directory = rtrim(DIR_IMAGE . '/' . str_replace('../', '', $_POST['directory']), '/');                               
                
                if (!is_dir($directory)) {
                    $json['error'] = 'Warning: Please select a directory!';
                }
                
                if (file_exists($directory . '/' . str_replace('../', '', $_POST['name']))) {
                    $json['error'] = 'Warning: A file or directory with the same name already exists!';
                }
            } else {
                $json['error'] = 'Warning: Please enter a new name!';
            }
        } else {
            $json['error'] = 'Warning: Please select a directory!';
        }
        /*
        if (!$this->user->hasPermission('modify', 'common/filemanager')) {
              $json['error'] = $this->language->get('error_permission');  
        }  */
        
        if (!isset($json['error'])) {    
            mkdir($directory . '/' . str_replace('../', '', $_POST['name']), 0777);
            
            $json['success'] = 'Success: Directory created!';
        }    
        
       $this->renderText(Json::encode($json));
    }
    
    
    public function actionDelete() {
        $json = array();
        
        if (isset($_POST['path'])) {
            $path = rtrim(DIR_IMAGE . '/' . str_replace('../', '', $_POST['path']), '/');
             
            if (!file_exists($path)) {
                $json['error'] = 'Warning: Please select a directory or file!';
            }
            
            if ($path == rtrim(DIR_IMAGE . '/', '/')) {
                $json['error'] = 'Warning: You can not delete this directory!';
            }
        } else {
            $json['error'] = 'Warning: Please select a directory or file!';
        }
        /*
        if (!$this->user->hasPermission('modify', 'common/filemanager')) {
              $json['error'] = $this->language->get('error_permission');  
        }  */
        
        if (!isset($json['error'])) {
            if (is_file($path)) {
                unlink($path);
            } elseif (is_dir($path)) {
                $this->recursiveDelete($path);
            }
            
            $json['success'] = 'Success: Your file or directory has been deleted!';
        }                
        
        $this->renderText(Json::encode($json));
    }

    protected function recursiveDelete($directory) {
        if (is_dir($directory)) {
            $handle = opendir($directory);
        }
        
        if (!$handle) {
            return false;
        }
        
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                if (!is_dir($directory . '/' . $file)) {
                    unlink($directory . '/' . $file);
                } else {
                    $this->recursiveDelete($directory . '/' . $file);
                }
            }
        }
        
        closedir($handle);
        
        rmdir($directory);
        
        return true;
    }
    
    public function actionRename() {
       
        $json = array();
        
        if (isset($_POST['path']) && isset($_POST['name'])) {
            if ((strlen(utf8_decode($_POST['name'])) < 3) || (strlen(utf8_decode($_POST['name'])) > 255)) {
                $json['error'] = 'Warning: Filename must be a between 3 and 255!';
            }
                
            $old_name = rtrim(DIR_IMAGE . '/' . str_replace('../', '', $_POST['path']), '/');
            
            if (!file_exists($old_name) || $old_name == DIR_IMAGE . 'data') {
                $json['error'] = 'Warning: Can not rename this directory!';
            }
            
            if (is_file($old_name)) {
                $ext = strrchr($old_name, '.');
            } else {
                $ext = '';
            }        
            
            $new_name = dirname($old_name) . '/' . str_replace('../', '', $_POST['name'] . $ext);
                                                                               
            if (file_exists($new_name)) {
                $json['error'] = 'Warning: A file or directory with the same name already exists!';
            }            
        }
        /*
        if (!$this->user->hasPermission('modify', 'common/filemanager')) {
              $json['error'] = $this->language->get('error_permission');  
        }
        */
        
        if (!isset($json['error'])) {
            rename($old_name, $new_name);
            
            $json['success'] = 'Success: Your file or directory has been renamed!';
        }
        $this->renderText(Json::encode($json));
    }
    
    public function actionImage() {
        if (isset($_POST['image'])) {
            $this->renderText(Yii::app()->request->baseUrl.$_POST['image']);
        }
    }

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}